package com.lej.share.core

import android.content.Context
import android.graphics.Bitmap
import com.lej.core.utils.extention.toast
import com.lej.share.BuildConfig
import com.lej.wx.PlatformUtil
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import java.io.ByteArrayOutputStream


object WxUtils {
    private fun Context.toWxApp(userName: String, path: String) {
        if (!checkInstallWx()) return
        WXAPIFactory.createWXAPI(this, BuildConfig.wx_id)
            .sendReq(WXLaunchMiniProgram.Req().also {
                it.userName = userName // 照妖镜小程序原始id
                it.path = path
                // 可选打开 开发版，体验版和正式版
                it.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE
            })
    }

    /**跳转微信照妖镜小程序*/
    fun toWxMirror(context: Context, uid: String? = null) {
        context.toWxApp("gh_38d61f812e5e", "/pages/appHome/index?channel=app&uid=$uid")
    }

    /**跳转微信测颜值小程序*/
    fun toWxFace(context: Context, uid: String? = null) {
        context.toWxApp("gh_5b0937696503", "/pages/home/index?channel=app&uid=$uid")
    }

    /**
     * 分享H5
     */
    fun shareWxWeb(
        context: Context,
        url: String,
        bitmap: Bitmap?,
        title: String,
        description: String
    ) {
        if (!context.checkInstallWx()) return
        //初始化一个WXWebpageObject，填写url
        val webpage = WXWebpageObject()
        webpage.webpageUrl = url

        //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
        val msg = WXMediaMessage(webpage)
        msg.title = title
//        bitmap?.let { bitmapToByte(it) }
        msg.description = description
//        msg.setThumbImage(bitmap?.let { compress(it) })
        msg.thumbData = bitmap?.let { Bitmap.createScaledBitmap(it,200,200,true) }
            ?.let { bitmapToByte(it) }
        //构造一个Req
        val req = SendMessageToWX.Req()
        req.transaction = ""
        req.message = msg
        req.scene = SendMessageToWX.Req.WXSceneSession//目前只支持会话
        req.userOpenId = BuildConfig.wx_id

        WXAPIFactory.createWXAPI(context, BuildConfig.wx_id).sendReq(req)
    }

    /**分享小程序*/
    fun shareWxSmallApp(
        context: Context,
        bitmap: Bitmap?,
        title: String,
        description: String,
        taskId: String,
        uid: String,
        nick: String,
        url: String? = null,
        from: Int,//1:任务详情 2:助力
    ) {
        if (!context.checkInstallWx()) return
        val miniProgramObj = WXMiniProgramObject().apply {
            webpageUrl = url ?: "http://www.qq.com" // 兼容低版本的网页链接
            miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE // 正式版:0，测试版:1，体验版:2
            userName = "gh_295327e6849e" // 小程序原始id
            //小程序页面路径；对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"
            path = "pages/task/index?task_id=${taskId}&uid=${uid}&name=${nick}$from=${from}"
        }
        val msg = WXMediaMessage(miniProgramObj).apply {
            this.title = title // 小程序消息title
            this.description = description // 小程序消息desc
            setThumbImage(bitmap)
        }
        val req = SendMessageToWX.Req().apply {
            transaction = ""
            message = msg
            scene = SendMessageToWX.Req.WXSceneSession//目前只支持会话
        }
        WXAPIFactory.createWXAPI(context, BuildConfig.wx_id).sendReq(req)
    }

    private fun Context.checkInstallWx() =
        if (PlatformUtil.isWeChatAvailable(this)) true
        else {
            "微信客户端似乎没有安装".toast();false
        }

    private fun bitmapToByte(bitmap: Bitmap):ByteArray{
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos)
        return baos.toByteArray()
    }

}
